/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.rest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.iisp.common.exception.I18nAppException;

/**
 * 类作用：
 * @author JohnnyZhou@cn.ibm.com
 * 使用说明：
 */
@ControllerAdvice
public class I18nAppExceptionHandler implements HandlerExceptionResolver {
	Logger log = LoggerFactory.getLogger(getClass());
	@Inject
	MessageSource messageSource;
	@Inject
	ObjectMapper objectMapper;

	@ExceptionHandler
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
		ModelAndView mv = new ModelAndView();
		/* 使用response返回 */
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); // 设置状态码
		response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
		response.setCharacterEncoding("UTF-8"); // 避免乱码
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		HashMap<String, Object> errorMessage = new HashMap<>();
		errorMessage.put("type", e.getClass().getSimpleName());
		errorMessage.put("defaultMessage", e.getMessage());
		if (e.getCause() != null) {
			errorMessage.put("cause", e.getCause().getMessage());
		}
		if (e instanceof I18nAppException) {
			I18nAppException i18nException = (I18nAppException) e;
			errorMessage.put("code", i18nException.getErrorCode());
			String messageKey = i18nException.getMessageKey();
			errorMessage.put("messageKey", messageKey);
			Locale lc = LocaleContextHolder.getLocale();
			String localizedMessage = messageSource.getMessage(messageKey, i18nException.getArgs(), null, lc);
			errorMessage.put("localizedMessage", localizedMessage);
		}
		try {
			objectMapper.writeValue(response.getWriter(), errorMessage);
		} catch (IOException e1) {
			log.error("转JSON错误：", e);
		}

		// log.debug("异常:" + ex.getMessage(), ex);
		return mv;
	}
}
